<script lang="ts">
  import {tweened} from "svelte/motion";
  import {linear} from "svelte/easing";
  import {onDestroy, onMount} from "svelte";
  import type {Point} from "./type";

  export let path: Point[] = []
  export let workable: boolean = false
  export let clientWidth = 1800
  export let clientHeight = 856
  export let width = 1800
  export let height = 856
  const intervalTime = 1000
  let i = 0

  const left = tweened(0, {
    duration: intervalTime,
    easing: linear
  })
  const top = tweened(0, {
    duration: intervalTime,
    easing: linear
  })

  function getXY([x, y]) {
    // 为了更好的适配不同长宽比的屏幕，地图图片使用了background-size:contain，所以在此区域长宽比和地图图片不一样时，图片周围会出现空白，
    // 当clientWidth较大时左右两侧出现空白，否则上下两侧出现空白，所有求出offset为偏移量，
    // rate为地图图片作为背景图缩放的比例，所以下方可以根据图片上位置点，算出像素的坐标点。
    if (clientWidth / clientHeight > width / height) {
      const rate = clientHeight / height
      const offset = (clientWidth - width * rate) / 2
      return [x * rate + offset, y * rate]
    } else {
      const rate = clientWidth / width
      const offset = (clientHeight - height * rate) / 2
      return [x * rate, y * rate + offset]
    }
  }
  let timer
  onMount(() => {
    timer = setInterval(() => {
      if (i === 0) {
        const [x, y] = getXY(path[i])
        left.set(x, {duration: 0})
        top.set(y, {duration: 0})
      }
      if (i < path.length) {
        const [x, y] = getXY(path[i])
        left.set(x)
        top.set(y)
        i++
      } else {
        i = 0
        const [x, y] = getXY(path[i])
        // console.log(i, path[i], x, y)
        left.set(x, {duration: 0})
        top.set(y, {duration: 0})
        // clearInterval(timer)
      }
    }, intervalTime)
  })
  onDestroy(() => {
    if (timer) {
      clearInterval(timer)
    }
  })
</script>
{#if i !== 0}
  <div class="absolute w-16 aspect-square point" class:workable={workable} style="left: {$left}px; top:{$top}px">
    <div class="w-full h-full bg-center bg-no-repeat bg-cover bg" class:animation={workable}></div>
    <div class="absolute inset-0 bg-center bg-no-repeat bg-cover point-img"></div>
  </div>
{/if}
<style>
  .point {
    margin-top: -2rem;
    margin-left: -2rem;
    transform: scale(.6);
  }
  .point.workable{
    transform: scale(1);
  }

  .point .bg {
    background-image: url('./point-light.png');
    opacity: 0;
  }

  .point .animation {
    animation: fadein 1s infinite;
  }

  .point-img {
    margin: 32%;
    background-image: url('./point.png');
  }

  @keyframes fadein {
    from {
      opacity: 0;
    }
    50% {
      opacity: 1;
    }
    to {
      opacity: 0;
    }
  }
</style>